package co.baiku.boot.live.baijiayun.util;

import co.baiku.boot.common.tools.EncryptTools;
import co.baiku.boot.common.tools.StringTools;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author haojiaolong
 * @date 2020/11/21 16:50
 */
public class BaiJiaSignUtil {

    /**
     * 构建签名
     *
     * @param map 参数
     * @param key 密钥key
     * @return
     */
    public static String buildSign(Map<String, Object> map, String key) {
        String[] keys = map.keySet().toArray(new String[0]);
        Arrays.sort(keys);
        StringBuilder sb = new StringBuilder();
        for (String k : keys) {
            if ("sign".equalsIgnoreCase(k)) {
                continue;
            }
            if (map.get(k) != null && map.get(k).toString().trim().length() > 0) {
                sb.append(k).append("=").append(map.get(k).toString().trim()).append("&");
            }
        }
        sb.append("partner_key=").append(key);
        return EncryptTools.md5(sb.toString()).toLowerCase();
    }

    /**
     * 验证签名
     *
     * @param params 参数
     * @param key    密钥可以
     * @return
     */
    public static boolean isValid(Map<String, String> params, String key) {
        String sign = params.get("sign");
        if (StringTools.isBlank(sign)) {
            return false;
        }
        Map<String, Object> collect = params.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        String sign1 = buildSign(collect, key);
        return sign.equalsIgnoreCase(sign1);
    }
}
